package com.boolib.scheck.aop.common.annotation.entity;



import com.boolib.scheck.aop.common.annotation.face.IUser;
import com.boolib.scheck.aop.common.exception.child.UserIsNotLoginException;
import com.boolib.scheck.aop.common.exception.child.UserNotPermissionsException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;


@Slf4j
@Aspect
@Component
@PropertySource(value = {"scheck.properties"})
public class LoginAspect {

    @Value("${check.auth}")
    private  String userAuth;



    @Pointcut("@annotation(com.boolib.scheck.aop.common.annotation.IsLogin)")
    public void isLogin(){}

    @Pointcut("@annotation(com.boolib.scheck.aop.common.annotation.IsAdmin)")
    public void isAdmin(){}

    @Before("isLogin()")
    public void authLogin () throws Throwable {


        HttpSession session =( (ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        IUser user = (IUser)session.getAttribute(userAuth);

        if(user == null){
            throw new UserIsNotLoginException("用户尚未登录");
        }


    }


    @Before("isAdmin()")
    public void authAdmin () throws Throwable {

        HttpSession session = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();

        IUser user = (IUser)session.getAttribute(userAuth);

        if(user == null){
            throw new UserIsNotLoginException("用户尚未登录");
        }

        if(!user.isAdmin()){
            throw  new UserNotPermissionsException("用户无权限");
        }

    }








}




